<?php
class Model_FlashPicture extends Model {    
	
	public $hashCategory;
	private  $uploadDir = "flashpic/";
	
	function __construct(){
		parent::__construct();
		$this->hashCategory = M('FlashPictureCategory')->getHash();
	}
	
    /**
     *在读取每条数据后...
     **/
	protected function _after_select_fetch(&$row){
		$row['_category'] = $this->hashCategory[$row['cid']];
		$row['_picture'] = URL_WEB . "Upload/" . $this->uploadDir . $row['id'] . '.' . $row['ext'];
	}
	
	function save($data){
		 //上传文件
    	$uploader = new Helper_FileUploader();

		$allowExts = 'jpg';
		$maxSize = 300 * 1024; // 300KB
		$uploadDir = PATH_APP_UPLOAD . $this->uploadDir;
		
		
		$uploader = new Helper_FileUploader();
		$files =& $uploader->getFiles();
		
		$file = current($files);
		
		if ($file && !$file->check($allowExts, $maxSize)) {
			// 上传的文件类型不符或者超过了大小限制。
			_message("你上传的文件类型不符或者超过了大小限制。");
			return false;
		}
		
		$file && $data['ext'] = $file->getExt();
		//=========================
		$id = parent::save($data); //保存数据，将返回的数据设为id
		!empty($data['id']) && $id = $data['id']; //如果是更新，则id为数据中的id，否则为返回值。
		//=========================
		if (!empty($file)) {
			Helper_FileSystem::rm($uploadDir . "$id.*");
			$filename = $id . '.' . strtolower($file->getExt());
			$file->move($uploadDir . $filename);
		}
	}
	
	
	
	function getListByCondition($conditionString){
		$pars = parse_pars($conditionString);
	
		$condition = array();
		$data = array();
		
		$exact = array();
			
		if($pars['type']){
			$exact['type'] = $pars['type'];
		}
		
		$conditions = $this->phaseConditions($like,$exact,$date,$range);
		
    	if (!empty($conditions)){
    		$sql_where .= ' and ' . join(" and ", $conditions);
    	}
		
		if($pars['order']){
			$sql_where .= " order by $pars[order] ";
		} else {
			$sql_where .= " order by name asc ";
		}
		//$pars['perpage']必须先于$pars['limit']的条件处理
		if($pars['perpage']){
			$total = $this->selectCount(" where 1 $sql_where");
			$pager = new Helper_Pager($total,$pars['perpage'],_gp('page','int'));
			$pars['limit'] = "{$pager->minimum} , {$pager->pagesize}";
			$data['pager'] = $pager->display;
		} 

		//$pars['limit']必须后于$pars['perpage']的条件处理
		if($pars['limit']){
			$sql_where .= " limit $pars[limit] ";
		}

		$list = $this->select("*", " where 1 $sql_where");

		foreach ($list as &$row){
			$row['subjectall'] = $row['subject'];
			if($pars['subjectlen']){
				$row['subject'] = _cutstr($row['subject'],$pars['subjectlen'],$pars['subjectdot']);
				if(!$pars['subjectdot'] && (substr($row['subject'], -1) == '.')){
					$row['subject'] = substr($row['subject'], 0, -1);
				}
			}
		}

		if($pars['perpage'] == ""){
			$data = $list;
		} else {
			$data['list'] = $list;
		}
		return $data;
	}
}
?>